#include "../include/Cart.h"
#include <float.h>

void cart::add_good(good a, bool sold) {
  for (auto &i : goods) {
    if (i == a && (!sold || (a.price == i.price))) {
      if (i.quantity < 0) {
        i.quantity = a.quantity;
      } else {
        i.quantity += a.quantity;
      }
      money += a.quantity * a.price;
#ifdef DEBUG
      printf("money : %lf\n", money);
#endif
      return;
    }
  }
  if (!goods.empty() && a.id == -1) {
    a.id = goods[goods.size() - 1].id + 1;
  }
#ifdef DEBUG
  puts("add_good:");
  std::cout << a << std::endl;
#endif
  goods.push_back(a);
  if (a.quantity > 0)
    money += a.quantity * a.price;
#ifdef DEBUG
  printf("money : %lf\n", money);
#endif
}
int cart::del_good(const good &a, int num) {
  auto it = goods.begin();
  for (; it != goods.end(); it++) {
    // std::cout << *it << std::endl << a << std::endl;
    if (*it == a && it->quantity > 0) {
      if (num == -1) {
        money -= (*it).quantity * (*it).price;
        it->quantity = -1;
        return 0; // 0 for success removed.
      } else if (num <= it->quantity) {
        it->quantity -= num;
        money -= num * it->price;
        return 0;
      } else {
        return -1; // -1 for too much goods required.
      }
    }
  }
  return -2; // -2 for good not found
}

void cart::to_file(std::ofstream &fs, int mode) {
  fs << "ID" << std::setw(10) << std::setfill(' ') << "名称" << std::setw(10)
     << std::setfill(' ') << "品牌" << std::setw(10) << std::setfill(' ')
     << "价格" << std::setw(10) << std::setfill(' ') << "数量";
  if (mode) {
    fs << std::setw(15) << std::setfill(' ') << "用户名";
  }
  fs << '\n';
  for (auto i : goods) {
    fs << i;
    fs << "\n";
  }
}

void cart::from_file(std::ifstream &fs, int mode) {
  std::string trash;
  std::getline(fs, trash);
  std::string tmp;
  good temp;
  while (std::getline(fs, tmp)) {
    if (tmp.empty())
      continue;
    std::istringstream s(tmp);
    if (mode) {
      s >> temp;
    } else {
      temp.from_stringstream(s);
    }
    add_good(temp);
  }
}